package com.adou.Controller;

import com.adou.common.controller.BaseController;
import com.adou.common.dto.*;
import com.adou.common.model.DefForm;
import com.adou.common.model.RunKeyForm;
import com.adou.common.util.Const;
import com.adou.service.FormModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 表单及模型设计控制器
 */
@Controller
@Scope(value = "prototype")
@RequestMapping(value = "/formmodel/")
public class FormModelController extends BaseController {

    @Autowired
    private FormModelService service;

    /**
     * 表单列表分页
     *
     * @param pageNum  页数
     * @param pageSize 页大小
     * @param flag     发布标记 0未发布 1已发布 不传为全部
     * @param keyWord  模糊查询：表单英文名称、表单中文名称、表单类型
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findByPage(int pageNum, int pageSize, Boolean flag, String keyWord) {
        try {
            DefForm defForm = new DefForm();
            defForm.setBflag(flag);
            defForm.setKeyWord(keyWord);
            Map<String, Object> map = service.findByPage(pageNum, pageSize, defForm);
            if ((long) map.get("totalcount") > 0) {
                List<DefForm> defFormList=(List<DefForm>)map.get("list");
                List<DefFormOutDto> defFormOutDtoList = defFormList.stream().map(DefFormOutDto::new).collect(Collectors.toList());
                map.put("list",defFormOutDtoList);
                resultMap.put("data", map);
                resultMap.put("msg", Const.DATA_SUCCEED);
            } else {
                resultMap.put("result", Const.LIST_ERROR_101);
                resultMap.put("msg", Const.DATA_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.LIST_ERROR_102);
            resultMap.put("msg", Const.DATA_FAIL);
        }
        return resultMap;
    }

    /**
     * 新建表单
     *
     *  @param o formname 表单英文名称;formdisplay 表单中文名称;formtype 表单类型;ver 表单版本;crttype 创建类型（默认0）     *
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(DefFormDto o) {
        try {
            DefForm defForm=new DefForm(o);
            int res = service.insertDefForm(defForm);
            if (res == 1) {
                resultMap.put("msg", Const.SAVE_SUCCEED);
            }
            else  if(res == 211){
                error(211,"表单英文名称为空");
            }
            else  if(res == 212){
                error(212,"表单类型错误");
            }
            else  if(res == 213){
                error(213,"表单中文名称为空");
            }
            else  if(res == 214){
                error(214,"表单已存在");
            }
            else {
                resultMap.put("result", Const.ADD_ERROR_201);
                resultMap.put("msg", Const.SAVE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.ADD_ERROR_202);
            resultMap.put("msg", Const.SAVE_FAIL);
        }
        return resultMap;
    }

    /**
     * 更新表单
     *
     * @param o id 表单id;formname 表单英文名称;formdisplay 表单中文名称;formtype 表单类型;ver 表单版本;crttype 创建类型（默认0）
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> update(DefFormDto o) {
        try {
            DefForm defForm=new DefForm(o);
            int res = service.updateDefForm(defForm);
            if (res == 1) {
                resultMap.put("msg", Const.UPDATE_SUCCEED);
            }
            else  if(res == 211){
                error(211,"表单英文名称为空");
            }
            else  if(res == 212){
                error(212,"表单类型错误");
            }
            else  if(res == 213){
                error(213,"表单中文名称为空");
            }
            else  if(res == 214){
                error(214,"表单已存在");
            }
            else  if(res == 215){
                error(215,"修改表单不存在");
            }
            else  if(res == 216){
                error(216,"表单已发布，无法修改");
            }
            else {
                resultMap.put("result", Const.UPDATE_ERROR_211);
                resultMap.put("msg", Const.UPDATE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.UPDATE_ERROR_212);
            resultMap.put("msg", Const.UPDATE_FAIL);
        }
        return resultMap;
    }

    /**
     * 表单发布
     *
     * @param formId 表单id
     */
    @RequestMapping(value = "deploy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deploy(Long formId) {
        try {
            DefForm defForm = new DefForm();
            defForm.setId(formId);
            int res = service.deployDefForm(defForm);
            if (res == 1) {
                resultMap.put("msg", Const.DEPLOY_SUCCEED);
            }
            else  if(res == 211){
                error(211,"发布表单不存在");
            }else  if(res == 212){
                error(212,"表单已发布");
            }else {
                resultMap.put("result", Const.DEPLOY_ERROR_221);
                resultMap.put("msg", Const.DEPLOY_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DEPLOY_ERROR_222);
            resultMap.put("msg", Const.DEPLOY_FAIL);
        }
        return resultMap;
    }

    /**
     * 撤销表单发布
     *
     * @param formId 表单id
     */
    @RequestMapping(value = "cancelDeploy", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> cancelDeploy(Long formId) {
        try {
            DefForm defForm = new DefForm();
            defForm.setId(formId);
            int res = service.cancelDefForm(defForm);
            if (res == 1) {
                resultMap.put("msg", Const.CANCEL_SUCCEED);
            }else  if(res == 211){
                error(211,"撤销发布表单不存在");
            }else  if(res == 212){
                error(212,"表单未发布");
            } else {
                resultMap.put("result", Const.CANCEL_ERROR_231);
                resultMap.put("msg", Const.CANCEL_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.CANCEL_ERROR_232);
            resultMap.put("msg", Const.CANCEL_FAIL);
        }
        return resultMap;
    }

    /**
     * 删除表单
     *
     * @param formId 表单id
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delete(Long formId) {
        try {
            DefForm defForm = new DefForm();
            defForm.setId(formId);
            int res = service.deleteDefForm(defForm);
            if (res == 1) {
                resultMap.put("msg", Const.DEL_SUCCEED);
            }else  if(res == 211){
                error(211,"删除表单不存在");
            }else  if(res == 212){
                error(212,"表单已发布");
            }  else {
                resultMap.put("result", Const.DEL_ERROR_301);
                resultMap.put("msg", Const.DEL_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DEL_ERROR_302);
            resultMap.put("msg", Const.DEL_FAIL);
        }
        return resultMap;
    }

    /**
     * 表单明细
     *
     * @param formId 表单id
     */
    @RequestMapping(value = "find", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> find(Long formId) {
        try {
            DefForm defForm = new DefForm();
            defForm.setId(formId);
            List<DefForm> list = service.find(defForm);
            if (list != null && list.size() > 0) {
                DefFormBigOutDto defFormBigOutDto=new DefFormBigOutDto(list.get(0));
                resultMap.put("data", defFormBigOutDto);
                resultMap.put("msg", Const.DATA_SUCCEED);
            } else {
                resultMap.put("result", Const.DATA_ERROR_111);
                resultMap.put("msg", Const.DATA_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DATA_ERROR_112);
            resultMap.put("msg", Const.DATA_FAIL);
        }
        return resultMap;
    }

    /**
     * 表单字段
     *
     * @param formId 表单id
     */
    @RequestMapping(value = "fields", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getFields(Long formId) {
        try {
            Map<String, Object> map = service.getFields(formId);
            if ((int) map.get("res") ==1) {
                resultMap.put("data", map.get("data"));
                resultMap.put("msg", Const.DATA_SUCCEED);
            }else {
                error((int)map.get("result"),map.get("msg").toString());
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DATA_ERROR_112);
            resultMap.put("msg", Const.DATA_FAIL);
        }
        return resultMap;
    }

    /**
     * 表单模型升版
     *
     * @param o 特别说明：这里的参数主要由前端formdesign设计器封装的js代码（formEdit.js）进行解析，具体作用详见formdesign设计器相关说明。
     *          formId 表单id;fieldNum 表单字段数;original 表单设计原始代码;parse 表单设计解析html;dataType 表单数据类型DataTypeDto数组（
     *          name;title;type;value;size;fieldname;plugins;orghide;fieldflow;orgalign;orgwidth;orgtype;style;content;orgrich;orgfontsize;parsename;
     *          options 复选框OptionsDto数组（name;value;type;checked;fieldname））;
     *
     */
    @RequestMapping(value = "upgradeDesin", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upgradeDesin(@RequestBody ParseHtmlDto o) {
        try {
            int res = service.upgradeDesin(o);
            if (res == 1) {
                resultMap.put("msg", Const.UPGRADE_SUCCEED);
            }
            else if(res == 0){
                error(res,"表单未发布");
            }
            else if(res == 211){
                error(res,"字段为空");
            }
            else if(res == 212){
                error(res,"字段重复");
            }
            else {
                resultMap.put("result", Const.UPGRADE_ERROR_241);
                resultMap.put("msg", Const.UPGRADE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.UPGRADE_ERROR_242);
            resultMap.put("msg", Const.UPGRADE_FAIL);
        }
        return resultMap;
    }

    /**
     * 表单模型设计
     *
     * @param o 特别说明：这里的参数主要由前端formdesign设计器封装的js代码（formEdit.js）进行解析，具体作用详见formdesign设计器相关说明。
     *          formId 表单id;fieldNum 表单字段数;original 表单设计原始代码;parse 表单设计解析html;dataType 表单数据类型DataTypeDto数组（
     *          name;title;type;value;size;fieldname;plugins;orghide;fieldflow;orgalign;orgwidth;orgtype;style;content;orgrich;orgfontsize;parsename;
     *          options 复选框OptionsDto数组（name;value;type;checked;fieldname））;
     */
    @RequestMapping(value = "updateDesign", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateDesign(@RequestBody ParseHtmlDto o) {
        try {
            int res = service.updateDesin(o);
            if (res == 1) {
                resultMap.put("msg", Const.SAVE_SUCCEED);
            }
            else if(res == 211){
                error(res,"字段为空");
            }
            else if(res == 212){
                error(res,"字段重复");
            } else {
                resultMap.put("result", Const.DESIGN_ERROR_251);
                resultMap.put("msg", Const.SAVE_FAIL);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DESIGN_ERROR_252);
            resultMap.put("msg", Const.SAVE_FAIL);
        }
        return resultMap;
    }

    /**
     * 是否在手机端显示
     * @param o id 主键 isShowOnTel 状态
     * @return
     */
    @RequestMapping(value = "showOrHide", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> showOrHide(RunKeyFormDto o){
        try{
            int res = service.showOrHide(o);
            if (res == 1) {
                resultMap.put("msg", "状态修改成功");
            }
            else if(res == 211){
                error(res,"主键为空");
            }
            else if(res == 212){
                error(res,"修改状态为空");
            } else {
                resultMap.put("result", Const.DESIGN_ERROR_251);
                resultMap.put("msg", Const.SAVE_FAIL);
            }
        }catch (Exception e){
            logger.error(e.toString(), e);
            resultMap.put("result", Const.DESIGN_ERROR_252);
            resultMap.put("msg", Const.SAVE_FAIL);
        }
        return resultMap;
    }

}

